package com.wu.threadPool;

import java.util.Vector;

/**
 * 线程池管理
 */
public class ThreadPoolManager {
    /**
     * 最大线程数
     */
    private int maxThreadCount;
    /**
     * Vector类可以实现可增长的对象数组
     */
    private final Vector<SimpleThread> vector;
    /**
     * 通知回调
     */
    private final Notify notify;

    public void setMaxThreadCount(int threadCount) {
        this.maxThreadCount = threadCount;
    }

    public ThreadPoolManager(int threadCount, Notify notify) {
        this.notify = notify;
        this.setMaxThreadCount(threadCount);
        //System.out.println("线程池开始运行了...");
        vector = new Vector<>();
        for (int i = 1; i <= threadCount; i++) {
            SimpleThread thread = new SimpleThread(i, this.notify);
            //将指定的组件添加到此向量的末尾，将其大小增加 1
            vector.addElement(thread);
            thread.start();
        }
        //System.out.println("初始化" + threadCount + "个线程完毕...");
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void process(Task task) {
        int i;
        //调用一个线程去处理，没有空闲线程就扩容
        for (i = 0; i < vector.size(); i++) {
            //返回指定索引处的组件
            SimpleThread currentThread = vector.elementAt(i);
            if (!currentThread.isRunning()) {
                //System.out.println("Thread" + (i + 1) + "开始执行新任务了");
                currentThread.setTask(task);
                //设置为true后，会在SimpleThread里面去执行
                currentThread.setRunning(true);
                return;
            }
        }
        //System.out.println("===================");
        //System.out.println("线程池中没有空闲的线程");
        //System.out.println("===================");
        if (i == vector.size()) {
            //扩容操作
            int temp = maxThreadCount;
            this.setMaxThreadCount(maxThreadCount + 10);
            for (int j = temp + 1; j <= maxThreadCount; j++) {
                SimpleThread thread = new SimpleThread(j, this.notify);
                vector.addElement(thread);
                thread.start();
            }
            //创建完之后需要重新执行 process
            this.process(task);
        }
    }
}

